<!DOCTYPE HTML>
<html lang="zh-Hans" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>从编解码层面理解WebSocket 手写一 个WebSocket - Rust 优秀博文</title>


        <!-- Custom HTML head -->
        
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="../../favicon.svg">
        <link rel="shortcut icon" href="../../favicon.png">
        <link rel="stylesheet" href="../../css/variables.css">
        <link rel="stylesheet" href="../../css/general.css">
        <link rel="stylesheet" href="../../css/chrome.css">
        <link rel="stylesheet" href="../../css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="../../fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="../../highlight.css">
        <link rel="stylesheet" href="../../tomorrow-night.css">
        <link rel="stylesheet" href="../../ayu-highlight.css">

        <!-- Custom theme stylesheets -->

    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "../../";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">1.</strong> 类型系统</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../01_类型系统/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow.html"><strong aria-hidden="true">1.1.</strong> Rust Concept Clarification Deref vs AsRef vs Borrow vs Cow</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow/Deref_AsRef_Borrow_Cow释义.html"><strong aria-hidden="true">1.2.</strong> Deref AsRef Borrow Cow 释义</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然/Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然.html"><strong aria-hidden="true">1.3.</strong> Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust的Cow类型有什么用？详解Cow及其用途/Rust的Cow类型有什么用？详解Cow及其用途.html"><strong aria-hidden="true">1.4.</strong> Rust的Cow类型有什么用？详解Cow及其用途</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/判别Fn、FnMut、FnOnce的标准/判别Fn、FnMut、FnOnce的标准.html"><strong aria-hidden="true">1.5.</strong> 判别Fn、FnMut、FnOnce的标准</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/一行代码告诉你内部可变性的真相(UnsafeCell)/一行代码告诉你内部可变性的真相(UnsafeCell).html"><strong aria-hidden="true">1.6.</strong> 一行代码告诉你内部可变性的真相(UnsafeCell)</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Tour_of_Rust's_Standard_Library_Traits/Tour_of_Rust's_Standard_Library_Traits.html"><strong aria-hidden="true">1.7.</strong> Tour of Rust's Standard Library Traits</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/逆变、协变与子类型，以及Rust/逆变、协变与子类型，以及Rust.html"><strong aria-hidden="true">1.8.</strong> 逆变、协变与子类型，以及Rust</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust自引用结构、Pin与Unpin/Rust自引用结构、Pin与Unpin.html"><strong aria-hidden="true">1.9.</strong> Rust自引用结构、Pin与Unpin</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/为什么Rust需要Pin,Unpin/为什么Rust需要Pin,Unpin.html"><strong aria-hidden="true">1.10.</strong> 译：为什么 Rust 需要 Pin, Unpin ？</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/定海神针Pin和Unpin/定海神针Pin和Unpin.html"><strong aria-hidden="true">1.11.</strong> 译：定海神针 Pin 和 Unpin</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/sizedness-in-rust/sizedness-in-rust.html"><strong aria-hidden="true">1.12.</strong> Sizedness in Rust</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust生命周期集大成者PhantomData〈T〉/Rust生命周期集大成者PhantomData〈T〉.html"><strong aria-hidden="true">1.13.</strong> Rust生命周期集大成者 PhantomData&lt;T&gt;</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操_Part_0.html"><strong aria-hidden="true">1.14.</strong> 数据库表达式执行的黑魔法：用Rust做类型体操 Part 0</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：GAT实现引用类型关联_Part_1.html"><strong aria-hidden="true">1.15.</strong> 数据库表达式执行的黑魔法：GAT实现引用类型关联 Part 1</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用HRTB写bound_Part_2.html"><strong aria-hidden="true">1.16.</strong> 数据库表达式执行的黑魔法：用HRTB写bound Part 2</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码_Part_3_&_4.html"><strong aria-hidden="true">1.17.</strong> 数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码 Part 3 & 4</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化_Part_5_&_6.html"><strong aria-hidden="true">1.18.</strong> 数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化 Part 5 & 6</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型_Part_7.html"><strong aria-hidden="true">1.19.</strong> 数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型 Part 7</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">2.</strong> 生命周期</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../02_生命周期/Rust中的生命周期——从StrSplit实例说开去/Rust中的生命周期——从StrSplit实例说开去.html"><strong aria-hidden="true">2.1.</strong> Rust中的生命周期——从StrSplit实例说开去</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/与ChatGPT深度对话来学Rust生命周期/与ChatGPT深度对话来学Rust生命周期.html"><strong aria-hidden="true">2.2.</strong> 与ChatGPT深度对话来学Rust生命周期</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——early_bound与late_bound（1）/进击的Rust生命周期——early_bound与late_bound（1）.html"><strong aria-hidden="true">2.3.</strong> 进击的Rust生命周期——early_bound与late_bound（1）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——early_bound与late_bound（2）/进击的Rust生命周期——early_bound与late_bound（2）.html"><strong aria-hidden="true">2.4.</strong> 进击的Rust生命周期——early_bound与late_bound（2）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——一力降十会的MIR（1）/进击的Rust生命周期——一力降十会的MIR（1）.html"><strong aria-hidden="true">2.5.</strong> 进击的Rust生命周期——一力降十会的MIR（1）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——一力降十会的MIR（2）/进击的Rust生命周期——一力降十会的MIR（2）.html"><strong aria-hidden="true">2.6.</strong> 进击的Rust生命周期——一力降十会的MIR（2）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/Common_Rust_Lifetime_Misconceptions/Common_Rust_Lifetime_Misconceptions.html"><strong aria-hidden="true">2.7.</strong> Common Rust Lifetime Misconceptions</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/Rust生命周期常见误区/Rust生命周期常见误区.html"><strong aria-hidden="true">2.8.</strong> 译：Rust生命周期常见误区</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">3.</strong> 无畏并发</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../05_无畏并发/简单写个Rust无锁队列/简单写个Rust无锁队列.html"><strong aria-hidden="true">3.1.</strong> 简单写个Rust无锁队列</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——混合自旋锁/进击的Rust多线程——混合自旋锁.html"><strong aria-hidden="true">3.2.</strong> 进击的Rust多线程——混合自旋锁</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/An_unsafe_tour_of_Rust's_Send_and_Sync/An_unsafe_tour_of_Rust's_Send_and_Sync.html"><strong aria-hidden="true">3.3.</strong> An unsafe tour of Rust's Send and Sync</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——Send与Sync/进击的Rust多线程——Send与Sync.html"><strong aria-hidden="true">3.4.</strong> 进击的Rust多线程——Send与Sync</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——离经叛道的PhantomData/进击的Rust多线程——离经叛道的PhantomData.html"><strong aria-hidden="true">3.5.</strong> 进击的Rust多线程——离经叛道的PhantomData</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust_Async_Pin概念解析/Rust_Async_Pin概念解析.html"><strong aria-hidden="true">3.6.</strong> Rust Async: Pin概念解析</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust和C++的并发库对比/Rust和C++的并发库对比.html"><strong aria-hidden="true">3.7.</strong> 译：Rust 和 C++ 的并发库对比</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust原子类型和内存排序/Rust原子类型和内存排序.html"><strong aria-hidden="true">3.8.</strong> Rust原子类型和内存排序</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">4.</strong> 网络编程</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../06_网络编程/从编解码层面理解WebSocket_手写一个WebSocket/从编解码层面理解WebSocket_手写一个WebSocket.html" class="active"><strong aria-hidden="true">4.1.</strong> 从编解码层面理解WebSocket 手写一 个WebSocket</a></li><li class="chapter-item expanded "><a href="../../06_网络编程/透过Rust探索系统的本原：网络篇/透过Rust探索系统的本原：网络篇.html"><strong aria-hidden="true">4.2.</strong> 透过Rust探索系统的本原：网络篇</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">5.</strong> 轮子系列</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../07_轮子系列/700行Rust写一个内存分配器/700行Rust写一个内存分配器.html"><strong aria-hidden="true">5.1.</strong> 700行Rust写一个内存分配器</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/Rust：网络库的实现思路/Rust：网络库的实现思路.html"><strong aria-hidden="true">5.2.</strong> Rust：网络库的实现思路</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/Rust异步运行时基础部件/Rust异步运行时基础部件.html"><strong aria-hidden="true">5.3.</strong> Rust异步运行时基础部件</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（1）.html"><strong aria-hidden="true">5.4.</strong> 使用Rust+epoll编写异步IO框架（1）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（2）.html"><strong aria-hidden="true">5.5.</strong> 使用Rust+epoll编写异步IO框架（2）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（3）.html"><strong aria-hidden="true">5.6.</strong> 使用Rust+epoll编写异步IO框架（3）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day1.html"><strong aria-hidden="true">5.7.</strong> 用rust从零开发一套web框架：day1</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day2.html"><strong aria-hidden="true">5.8.</strong> 用rust从零开发一套web框架：day2</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day3.html"><strong aria-hidden="true">5.9.</strong> 用rust从零开发一套web框架：day3</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day4.html"><strong aria-hidden="true">5.10.</strong> 用rust从零开发一套web框架：day4</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day5.html"><strong aria-hidden="true">5.11.</strong> 用rust从零开发一套web框架：day5</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">6.</strong> 奇技淫巧</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Copy-On-Write是不是优化？/Copy-On-Write是不是优化？.html"><strong aria-hidden="true">6.1.</strong> 译：Copy-On-Write是不是优化？</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/揭秘神奇的Rust_Axum风格的函数实现/揭秘神奇的Rust_Axum风格的函数实现.html"><strong aria-hidden="true">6.2.</strong> 译：揭秘神奇的 Rust Axum 风格的函数实现</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/“变长参数”函数与回调/“变长参数”函数与回调.html"><strong aria-hidden="true">6.3.</strong> “变长参数”函数与回调</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Rust字符串格式化的幕后：format_args!()/Rust字符串格式化的幕后：format_args!().html"><strong aria-hidden="true">6.4.</strong> 译：Rust字符串格式化的幕后：format_args!()</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/给Rust带来一点C++特产/给Rust带来一点C++特产.html"><strong aria-hidden="true">6.5.</strong> 给Rust带来一点C++特产</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/一步步实现_Rust_Bevy_ECS_的_System_简化版本/一步步实现_Rust_Bevy_ECS_的_System_简化版本.html"><strong aria-hidden="true">6.6.</strong> 一步步实现 Rust Bevy ECS 的 System 简化版本</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples.html"><strong aria-hidden="true">6.7.</strong> Exploring Design Patterns in Rust with Algorithmic Trading Examples</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">7.</strong> 源码分析</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：bytes源码分析/Rust并发：bytes源码分析.html"><strong aria-hidden="true">7.1.</strong> Rust并发：bytes源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：标准库Arc源码分析/Rust并发：标准库Arc源码分析.html"><strong aria-hidden="true">7.2.</strong> Rust并发：标准库Arc源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：标准库sync_Once源码分析/Rust并发：标准库sync_Once源码分析.html"><strong aria-hidden="true">7.3.</strong> Rust并发：标准库sync::Once源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust源码阅读：引用计数Rc/Rust源码阅读：引用计数Rc.html"><strong aria-hidden="true">7.4.</strong> Rust源码阅读：引用计数Rc</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust源码阅读：Cell、RefCell与内部可变性/Rust源码阅读：Cell、RefCell与内部可变性.html"><strong aria-hidden="true">7.5.</strong> Rust源码阅读： Cell、RefCell与内部可变性</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/关于_Rust_的_UnsafeCell、Cell_与_RefCell/关于_Rust_的_UnsafeCell、Cell_与_RefCell.html"><strong aria-hidden="true">7.6.</strong> 关于 Rust 的 UnsafeCell、Cell 与 RefCell</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust_Async_async-stream源码分析/Rust_Async_async-stream源码分析.html"><strong aria-hidden="true">7.7.</strong> Rust Async: async-stream源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/走进Tokio的异步世界/走进Tokio的异步世界.html"><strong aria-hidden="true">7.8.</strong> 走进 Tokio 的异步世界</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/tokio.rs_runtime的实现/tokio.rs_runtime的实现.html"><strong aria-hidden="true">7.9.</strong> tokio.rs runtime 的实现</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_internals/Tokio_internals.html"><strong aria-hidden="true">7.10.</strong> Tokio internals</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_internals/译文：Tokio內部机制.html"><strong aria-hidden="true">7.11.</strong> 译：Tokio 内部机制</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust_Axum_HTTP_框架的架构分析/Rust_Axum_HTTP_框架的架构分析.html"><strong aria-hidden="true">7.12.</strong> Rust Axum HTTP 框架的架构分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/安利一个Rust_Game_Engine：Bevy--ECS部分/安利一个Rust_Game_Engine：Bevy--ECS部分.html"><strong aria-hidden="true">7.13.</strong> 安利一个Rust Game Engine：Bevy--ECS部分</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_解析之任务调度/Tokio_解析之任务调度.html"><strong aria-hidden="true">7.14.</strong> Tokio 解析之任务调度</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">8.</strong> 生态观察</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../11_生态观察/Rust_web_frameworks_have_subpar_error_reporting/Rust_web_frameworks_have_subpar_error_reporting.html"><strong aria-hidden="true">8.1.</strong> Rust web frameworks have subpar error reporting</a></li><li class="chapter-item expanded "><a href="../../11_生态观察/SeaORM：要做Rust版本的ActiveRecord/SeaORM：要做Rust版本的ActiveRecord.html"><strong aria-hidden="true">8.2.</strong> SeaORM：要做Rust版本的ActiveRecord</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">9.</strong> 死灵终极</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_总述.html"><strong aria-hidden="true">9.1.</strong> 译：Learn Rust the Dangerous Way 总述</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_0.html"><strong aria-hidden="true">9.2.</strong> 译：Learn Rust the Dangerous Way 0</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_1.html"><strong aria-hidden="true">9.3.</strong> 译：Learn Rust the Dangerous Way 1</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_2.html"><strong aria-hidden="true">9.4.</strong> 译：Learn Rust the Dangerous Way 2</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_3.html"><strong aria-hidden="true">9.5.</strong> 译：Learn Rust the Dangerous Way 3</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_4.html"><strong aria-hidden="true">9.6.</strong> 译：Learn Rust the Dangerous Way 4</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_5.html"><strong aria-hidden="true">9.7.</strong> 译：Learn Rust the Dangerous Way 5</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（一）.html"><strong aria-hidden="true">9.8.</strong> Unsafe Rust 随堂小测（一）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（二）.html"><strong aria-hidden="true">9.9.</strong> Unsafe Rust 随堂小测（二）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（三）.html"><strong aria-hidden="true">9.10.</strong> Unsafe Rust 随堂小测（三）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测参考答案.html"><strong aria-hidden="true">9.11.</strong> Unsafe Rust 随堂小测参考答案</a></li></ol></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">Rust 优秀博文</h1>

                    <div class="right-buttons">
                        <a href="../../print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="从编解码层面理解-websocket-手写一-个websocketrust"><a class="header" href="#从编解码层面理解-websocket-手写一-个websocketrust">从编解码层面理解 WebSocket ，手写一 个WebSocket（Rust）</a></h1>
<p>作者：<a href="https://juejin.cn/user/3227821868334919/posts">asyncrustacean</a></p>
<p>原载：<a href="https://juejin.cn/post/7293935529198895155">https://juejin.cn/post/7293935529198895155</a></p>
<blockquote>
<p>本文旨在彻底讲清楚 websocket 是如何在 tcp 上面进行握手和数据传输的，并且用代码实现一个 ws server，希望读者看完这篇文章后彻底理解 websocket</p>
</blockquote>
<h2 id="websocket-rfc"><a class="header" href="#websocket-rfc">websocket rfc</a></h2>
<p>有兴趣的同学可以去看下完整的 <a href="https://link.juejin.cn/?target=https%3A%2F%2Fdatatracker.ietf.org%2Fdoc%2Fhtml%2Frfc6455">websocket rfc</a></p>
<p>这里我只对重要的部分介绍</p>
<h3 id="握手阶段"><a class="header" href="#握手阶段">握手阶段</a></h3>
<p>当在浏览器里执行 <code>new Websocket(&quot;ws://localhost:8080&quot;)</code> 的时候</p>
<p>浏览器首先会和服务器建立一个 tcp 连接，在 tcp 上传输 http 报文进行握手，具体的请求报文内容如下图所示</p>
<p><img src="pict/001.webp" alt="" /></p>
<p>其中有几个特殊的 header 字段，分别是</p>
<ol>
<li><code>Upgrade: websocket</code></li>
<li><code>Connection: Upgrade</code></li>
<li><code>Sec-WebSocket-Protocol</code></li>
<li><code>Sec-WebSocket-Key</code></li>
<li><code>Sec-WebSocket-Version</code></li>
</ol>
<p>其中 1，2 是固定的</p>
<p><code>Sec-WebSocket-Protocol</code> 是客户端列举的一些子协议，服务端可以选择其中的一个或多个返回</p>
<p><code>Sec-WebSocket-Key</code> 是客户端随机生成的( 先随机生成 16 字节的数据, 然后 base64 )，服务端需要将该字段的值拼接上一个固定的值<code>258EAFA5-E914-47DA-95CA-C5AB0DC85B11</code>, 然后用 sha-1 hash算法得到 hash 结果，再进行 base64 编码，结果放在响应头 <code>Sec-WebSocket-Accept</code> 返回</p>
<p>比如 <code>Sec-WebSocket-Key</code> 的值是 <code>dGhlIHNhbXBsZSBub25jZQ==</code> ，拼接得到 <code>dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-C5AB0DC85B11</code>，将该值 sha1 hash 再 base64 得到 <code>s3pPLMBiTxaQ9kYGzzhZRbK+xOo=</code>，就是 <code>Sec-WebSocket-Accept</code> 的值</p>
<p>除了这些以外, 还有 <code>Sec-WebSocket-Extensions</code>, 表示一些扩展协议, <strong>本文不讨论扩展协议</strong></p>
<p>响应的头信息如下图</p>
<p><img src="pict/002.webp" alt="" /></p>
<p>对应的字段都解释过了，需要注意的是响应状态码是 101, 所以整个握手的流程如下所示</p>
<p><img src="pict/003.png" alt="" /></p>
<h3 id="传输数据"><a class="header" href="#传输数据">传输数据</a></h3>
<p>ws 通过在 tcp 传输一个个 <code>frame</code> 来传输消息, 具体 <code>frame</code> 的定义如下图</p>
<p><img src="pict/004.webp" alt="" /></p>
<p><code>frame</code>的格式实际上非常简单, 具体字段我一个个来解释</p>
<h4 id="fin"><a class="header" href="#fin">fin</a></h4>
<p>第一个 bit 是 fin, 用来标识该 <code>frame</code> 是否是一个消息体里面的最后一个, 如果该消息体只有一个 <code>frame</code>, 那么 fin 也是 1</p>
<h4 id="rsv1rsv2rsv3"><a class="header" href="#rsv1rsv2rsv3">rsv1,rsv2,rsv3</a></h4>
<p>rsv1,rsv2,rsv3, 这三个一般都是 0, 各 1bit 大小, 除非有扩展协议指定他们的值</p>
<h4 id="opcode"><a class="header" href="#opcode">opcode</a></h4>
<p>opcode 指定了 payload data 的类型, 一共 4 bit</p>
<ul>
<li>0 表示这是一组连续的<code>frame</code> 其中的一个,和前面的 <code>frame</code> 合并</li>
<li>1 表示这是文本消息(text)</li>
<li>2 表示这是二进制消息</li>
<li>3-7 是保留的类型</li>
<li>8 关闭消息, 通知对端即将关闭</li>
<li>9 ping 消息, 用来测活</li>
<li>0xa pong 消息, 用来响应 ping 消息</li>
<li>0xb-0xf 是保留的类型</li>
</ul>
<h4 id="mask"><a class="header" href="#mask">mask</a></h4>
<p>mask 表明 payload data 是否被<strong>掩码</strong>, 大小 1bit, 什么是掩码后面会提到</p>
<ol>
<li>如果是客户端发往服务端的消息, 必须要进行掩码</li>
<li>如果是服务端发往客户端的消息, 必须不掩码</li>
</ol>
<p>如果违反了上面的规则, 那么连接必须要断开</p>
<h4 id="payload-length"><a class="header" href="#payload-length">payload length</a></h4>
<p>首先读取 7bit 的数字, 如果在 0-125 之间,那么就是 payload length</p>
<p>如果是 126, 那么读取后面 2 个字节的数字作为 payload length</p>
<p>如果是 127, 读取后面 8 个字节的数字作为 payload length</p>
<h4 id="masking-key"><a class="header" href="#masking-key">masking key</a></h4>
<p>如果 mask 是 1, 那么就有 4 字节的 masking key, 否则该字段不存在</p>
<h4 id="payload-data-和掩码"><a class="header" href="#payload-data-和掩码">payload data 和掩码</a></h4>
<p>如果 mask 是 1, 那么 payload data 就是被掩码的, 具体掩码的规则是:</p>
<p>假设 i 表示是 payload data 第 i 个字节</p>
<p>j 为 i % 4 , 也就是对 4 取余</p>
<p>将masking key 第 j 位的数字和 payload 第 i 位的数字做异或, 就是掩码后 payload data 第 i 位的数字</p>
<p>掩码的具体内容后面代码会提到</p>
<h3 id="总结"><a class="header" href="#总结">总结</a></h3>
<p>现在我们对整个 ws 的传输过程了解的差不多了, 下一步就是编码实现</p>
<h2 id="实现一个-websocket-server"><a class="header" href="#实现一个-websocket-server">实现一个 WebSocket Server</a></h2>
<p>本文用 rust 实现, 如果你不懂 rust, 也不要担心, 不同语言之间的实现都是差不多的(你肯定看得懂), 如果你想学习 rust 可以去<a href="https://link.juejin.cn/?target=https%3A%2F%2Fdoc.rust-lang.org%2Fbook%2F">这里</a></p>
<p>代码除了用 ring 和 base64 这两个 crate, 就没有用其他 crate 了, 代码只是为了最快实现 ws 的传输过程, 不考虑性能等其他问题</p>
<h3 id="实现握手环节"><a class="header" href="#实现握手环节">实现握手环节</a></h3>
<p>首先搭建一个 tcp 服务器</p>
<pre><pre class="playground"><code class="language-rust">rust复制代码use std::{
    error::Error,
    io::{BufRead, BufReader, BufWriter, Write},
    net::TcpListener,
};

fn main() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
    let listener = TcpListener::bind(&quot;0.0.0.0:8080&quot;)?;

    while let Ok((stream, _)) = listener.accept() {
        let mut reader = BufReader::new(&amp;stream);
        let mut writer = BufWriter::new(&amp;stream);
        handshake(&amp;mut reader, &amp;mut writer)?;
    }

    Ok(())
}

fn handshake(reader: &amp;mut impl BufRead, writer: &amp;mut impl Write) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
    // 在这里编写握手的过程
    Ok(())
}
</code></pre></pre>
<p>在握手阶段写一个简单的 http parser 即可, 重点是获取 <code>sec-websocket-key</code>, 然后计算出 <code>sec-websocket-accept</code> 字段,并返回响应体, 完成握手</p>
<p>完整的代码如下所示</p>
<pre><pre class="playground"><code class="language-rust">rust复制代码use base64::{engine::general_purpose, Engine as _};
use ring::digest;
use std::{
    collections::BTreeMap,
    error::Error,
    io::{self, BufRead, BufReader, BufWriter, Write},
    net::TcpListener,
};

fn main() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
    let listener = TcpListener::bind(&quot;0.0.0.0:8080&quot;)?;

    while let Ok((stream, _)) = listener.accept() {
        let mut reader = BufReader::new(&amp;stream);
        let mut writer = BufWriter::new(&amp;stream);
        handshake(&amp;mut reader, &amp;mut writer)?;
    }

    Ok(())
}

// 握手
fn handshake(reader: &amp;mut impl BufRead, writer: &amp;mut impl Write) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
    let mut buffer = String::new();
    let size = reader.read_line(&amp;mut buffer)?;
    // 读取 http 请求行
    let request_line: &amp;str = &amp;buffer[0..size];
    let _ = request_line;
    buffer.truncate(0);

    let mut headers = BTreeMap::&lt;String, String&gt;::new();

    loop {
        let size = reader.read_line(&amp;mut buffer)?;
        // 读取每一个头信息
        let header_line: &amp;str = &amp;buffer[0..size];
        // 头信息完结
        if header_line == &quot;\r\n&quot; {
            break;
        }

        let header_line = &amp;header_line[0..(size - 2)];

        if let Some((k, v)) = header_line.split_once(':') {
            headers.insert(k.to_lowercase(), v.trim_start().into());
        };

        buffer.truncate(0);
    }

    let sec_websocket_key = headers.get(&quot;sec-websocket-key&quot;).ok_or(io::Error::new(
        io::ErrorKind::ConnectionRefused,
        &quot;no header Sec-Websocket-Key&quot;,
    ))?;

    const UUID: &amp;[u8] = b&quot;258EAFA5-E914-47DA-95CA-C5AB0DC85B11&quot;;

    // sha1 加 base64
    let concat_str = [sec_websocket_key.as_bytes(), UUID].concat();
    let hash_result = digest::digest(&amp;digest::SHA1_FOR_LEGACY_USE_ONLY, &amp;concat_str);
    let sec_websocket_accept = general_purpose::STANDARD.encode(hash_result.as_ref());

    let response = format!(
        &quot;HTTP/1.1 101 Switching Protocols\r\n\
        Upgrade: websocket\r\n\
        Connection: Upgrade\r\n\
        Sec-WebSocket-Accept: {}\r\n\r\n&quot;,
        sec_websocket_accept
    );

    writer.write_all(response.as_bytes())?;

    writer.flush()?;

    Ok(())
}
</code></pre></pre>
<p>cargo run 将服务启动起来，然后在浏览器控制台输入</p>
<pre><code class="language-js">js复制代码const ws = new WebSocket(&quot;ws://localhost:8080/&quot;)

ws.addEventListener(&quot;open&quot;, () =&gt; {
  console.log(&quot;open&quot;)
})
</code></pre>
<p>你会看到</p>
<p><img src="pict/005.webp" alt="" /></p>
<p>说明 websocket 已经成功通过了握手的环节</p>
<h3 id="实现消息的编码和解码"><a class="header" href="#实现消息的编码和解码">实现消息的编码和解码</a></h3>
<p>先定义两种消息</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>rust复制代码enum Message {
    Text(String), // 文本消息
    Binary(Vec&lt;u8&gt;), // 二进制消息
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="消息的编码"><a class="header" href="#消息的编码">消息的编码</a></h3>
<p>我们开始将消息编码成一个 <code>frame</code>, 如果你不知道消息的具体长度（比如流），你可以用多个 <code>frame</code> 将消息切片发送, 这里不考虑这个问题</p>
<p>开始定义 <code>message</code> 的编码方法, 因为<strong>服务端发往客户端的消息不掩码</strong>, 实现起来就很简单</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>rust复制代码impl Message {
    fn as_bytes(&amp;self) -&gt; &amp;[u8] {
        match &amp;self {
            Message::Binary(data) =&gt; data,
            Message::Text(data) =&gt; data.as_bytes(),
        }
    }
    
    // opcode  表示当前的消息类型
    fn opcode(&amp;self) -&gt; u8 {
        match &amp;self {
            Message::Binary(_) =&gt; 2,
            Message::Text(_) =&gt; 1,
        }
    }

    fn encode(&amp;self) -&gt; Vec&lt;u8&gt; {
        let payload_data = self.as_bytes();
        let payload_length = payload_data.len() as u64;

        // 初始的长度是 2个 字节 fin,rsv1...payload_length
        let mut total_frame_length = 2;

        if payload_length &gt; 125 {
            // 扩展 payload_length
            if payload_length &gt; u16::MAX as u64 {
                total_frame_length += 8;
            } else {
                total_frame_length += 2;
            }
        }

        total_frame_length += payload_length;

        let mut frame: Vec&lt;u8&gt; = Vec::with_capacity(total_frame_length as usize);

        let opcode = self.opcode();
        frame.push(0b1000_0000); // fin 是 1
        frame[0] |= opcode;

        if payload_length &lt;= 125 {
            frame.push(payload_length as u8);
        } else if payload_length &gt; u16::MAX as u64 {
            frame.push(127);
            frame.extend_from_slice(&amp;payload_length.to_be_bytes());
        } else {
            frame.push(126);
            frame.extend_from_slice(&amp;(payload_length as u16).to_be_bytes());
        }

        // 服务端不需要 mask, 直接拼接数据
        frame.extend_from_slice(payload_data);

        frame
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>验证一下这个编码是否正确, 新增一个 <code>handle_connection</code> 函数, 分别向客户端发送 大,中,小 三种长度的文本消息,还有一个大的二进制消息, 在客户端验证这个效果</p>
<p>服务端的代码</p>
<pre><pre class="playground"><code class="language-rust">rust复制代码
fn main() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
    let listener = TcpListener::bind(&quot;0.0.0.0:8080&quot;)?;

    while let Ok((stream, _)) = listener.accept() {
        let mut reader = BufReader::new(&amp;stream);
        let mut writer = BufWriter::new(&amp;stream);
        handshake(&amp;mut reader, &amp;mut writer)?;
        handle_connection(&amp;mut reader, &amp;mut writer)?;
    }

    Ok(())
}

fn handle_connection(
    reader: &amp;mut impl BufRead,
    writer: &amp;mut impl Write,
) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
    let message = Message::Text(&quot;hello from server side&quot;.into());
    writer.write_all(&amp;message.encode())?;

    let middle_message = Message::Text(String::from_utf8_lossy(&amp;[b'*'; 126]).to_string());
    writer.write_all(&amp;middle_message.encode())?;

    let big_message =
        Message::Text(String::from_utf8_lossy(&amp;[b'*'; (u16::MAX as usize + 1)]).to_string());
    writer.write_all(&amp;big_message.encode())?;

    let big_binary_message = Message::Binary(vec![b'*'; u16::MAX as usize + 1]);

    writer.write_all(&amp;big_binary_message.encode())?;

    writer.flush()?;
    Ok(())
}
</code></pre></pre>
<p>客户端的代码</p>
<pre><code class="language-javascript">javascript复制代码const ws = new WebSocket(&quot;ws://localhost:8080/&quot;)
ws.addEventListener(&quot;message&quot;, (ev) =&gt; {
  if (ev.data instanceof Blob) {
    // 二进制数据
    console.log({
      messageLength: ev.data.size,
      messageType: &quot;binary&quot;,
      messageData: ev.data,
    })
  } else {
    // 文本消息
    console.log({
      messageLength: ev.data.length,
      messageType: &quot;text&quot;,
      messageData: ev.data,
    })
  }
})
</code></pre>
<p>重新启动服务, 并在控制台运行这段代码, 不出意外的话, 你可以看到输出</p>
<p><img src="pict/006.webp" alt="" /></p>
<p>说明我们的服务已经可以正确的编码并向客户端发送消息了</p>
<h3 id="消息的解码"><a class="header" href="#消息的解码">消息的解码</a></h3>
<p>从客户端发往服务端的所有消息都是掩码的, ws 的掩码使用异或算法, 异或算法的特性是对同一个数字异或两次会还原数字, 服务端在接收消息的时候要还原数据, 代码如下</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>rust复制代码
fn decode_message(reader: &amp;mut impl BufRead) -&gt; Result&lt;Message, Box&lt;dyn Error&gt;&gt; {
    let mut buffer = [0; 2];
    // 先获取前面两个字节
    reader.read_exact(&amp;mut buffer)?;

    // 不考虑 fin 不为 1 的情况, 一次读取一个 frame 然后拼接成 message
    let opcode = buffer[0] &amp; 0b1111;
    let mask = buffer[1] &gt;&gt; 7;
    if mask != 1 {
        // 客户端发来的消息必须是掩码的
        return Err(io::Error::new(io::ErrorKind::ConnectionRefused, &quot;mask require&quot;).into());
    }

    let mut payload_length = (buffer[1] &amp; 0b0111_1111) as u64;

    if payload_length == 126 {
        reader.read_exact(&amp;mut buffer)?;
        payload_length = u16::from_be_bytes(buffer) as u64;
    } else if payload_length == 127 {
        let mut buffer = [0; 8];
        reader.read_exact(&amp;mut buffer)?;
        payload_length = u64::from_be_bytes(buffer);
    }

    let mut mask_key = [0; 4];
    reader.read_exact(&amp;mut mask_key)?;

    let mut payload_data: Vec&lt;u8&gt; = vec![0; payload_length as usize];
    reader.read_exact(&amp;mut payload_data)?;

    // 还原原始的 payload_data
    (0..payload_data.len()).for_each(|i| {
        let j = i % 4;
        let cur_mask_key = mask_key[j];
        payload_data[i] ^= cur_mask_key;
    });

    Ok(if opcode == 1 {
        Message::Text(String::from_utf8_lossy(&amp;payload_data).to_string())
    } else {
        Message::Binary(payload_data)
    })
}
<span class="boring">}
</span></code></pre></pre>
<p>测试一下, 更改 <code>handle_connection</code> 如下</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>rust复制代码fn handle_connection(
    reader: &amp;mut impl BufRead,
    writer: &amp;mut impl Write,
) -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
    while let Ok(message) = decode_message(reader) {
        match message {
            Message::Text(text) =&gt; {
                println!(&quot;{text}&quot;);
            }
            Message::Binary(data) =&gt; {
                println!(&quot;{data:?}&quot;)
            }
        }
    }
    Ok(())
}
<span class="boring">}
</span></code></pre></pre>
<p>客户端代码如下, 控制台里面调用</p>
<pre><code class="language-javascript">javascript复制代码const ws = new WebSocket(&quot;ws://localhost:8080/&quot;)
ws.onopen = () =&gt; {
  ws.send(&quot;hello from client side&quot;)
  ws.send(&quot;*&quot;.repeat(127))
  ws.send(&quot;*&quot;.repeat(65536))
}
</code></pre>
<p>服务端的输出结果如下</p>
<p><img src="pict/007.webp" alt="" /></p>
<p>证明解码也没问题</p>
<h2 id="总结-1"><a class="header" href="#总结-1">总结</a></h2>
<p>具体的代码放在<a href="https://link.juejin.cn/?target=https%3A%2F%2Fgithub.com%2Fswnb%2Fws-echo-server">github</a>上面了, 希望对大家有帮助, 能更好的理解 websocket 的传输过程, 谢谢大家</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="../../empty.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>

                            <a rel="next" href="../../06_网络编程/透过Rust探索系统的本原：网络篇/透过Rust探索系统的本原：网络篇.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="../../empty.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

                    <a rel="next" href="../../06_网络编程/透过Rust探索系统的本原：网络篇/透过Rust探索系统的本原：网络篇.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>




        <script type="text/javascript">
            window.playground_copyable = true;
        </script>


        <script src="../../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../searcher.js" type="text/javascript" charset="utf-8"></script>

        <script src="../../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->


    </body>
</html>
